package com.whnk.workflow.utils;

import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

/**
 * 工作流工具类
 * 
 * @author ASUS
 *
 */
public class WorkflowUtils {

	//调用引擎初始化
    private static ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    
    /**
     * 部署流程定义
     */
    public static Deployment deploy(String name, String bpmnPath, String pngPath) {
        Deployment deployment = processEngine.getRepositoryService()//管理流程定义Service
        		.createDeployment()//创建一个部署对象
        		.name(name)//部署对象命名
        		.addClasspathResource(bpmnPath)//从classpath下加载资源，一次一个
        		.addClasspathResource(pngPath)
        		.deploy();//完成部署
        return deployment;
    }
    
    public static void main(String[] args) {
    	deploy("leave请假申请", "diagrams/leave.bpmn", "diagrams/leave.png");
    }
    
    /**
     * 启动流程实例
     */
    public static ProcessInstance startProcessInstance(String processDefinitionKey, String businessKey, Map<String, Object> map) {
        ProcessInstance processInstance = processEngine.getRuntimeService()//执行管理，包括启动、推进、删除流程实例等操作Service
                .startProcessInstanceByKey(processDefinitionKey, businessKey, map);//根据businessKey值来查询流程，也可以根据processDefinitionKey
        return processInstance;
    }
    
    /**
     * 查询当前个人任务
     */
    public static List<Task> fingByAssignee(String assignee) {
        List<Task> taskList = processEngine.getTaskService()//任务管理Service
                .createTaskQuery()//创建任务查询对象
                .taskAssignee(assignee)//指定个人任务查询，指定代理人
                .orderByTaskCreateTime()//按任务创建时间排序
                .desc()//倒序排列
                .list();//以list形式记录对象
        return taskList;
    }
    
    /**
     * 完成当前个人任务
     */
    public static void complete(String taskId, Map<String, Object> map) {
        processEngine.getTaskService()//任务管理Service
            .complete(taskId, map);
    }
    
    /**
     * 根据businessKey查询当前任务
     * 
     * @param businessKey
     * @return
     */
    public static Task findTaskByBusinessKey(String businessKey) {
    	List<Task> taskList = processEngine.getTaskService()//任务管理Service
    			.createTaskQuery()//创建任务查询对象
    			.processInstanceBusinessKey(businessKey)//根据businessKey查询当前任务
    			.list();//以list形式记录对象
    	return taskList != null && taskList.size() > 0 ? taskList.get(0) : null;
    }
}
